#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Wild Orange
# @Email: jixuanfan_seu@163.com
# @Date:   2020-06-19 22:38:14
# @Last Modified time: 2020-07-03 10:04:45

import requests
import re
import json

headers={'User-Agent': 'Chrome/76.0.3809.132'}

#正则表达式提取数据
re_get_js=re.compile(r'<script>([\s\S]*?)</script>')
re_resultList=re.compile(r'"resultList":(\[{.+?}\]),"totalNumFound')
has_statement=False

def Get_company_info(name):
	'''
		@func: 通过百度企业信用查询企业基本信息
	'''
	url='https://xin.baidu.com/s?q=%s'%name
	res=requests.get(url,headers=headers)
	if __check() and res.status_code==200:
		html=res.text
		retVal=_parse_baidu_company_info(html)
		return retVal
	else:
		print('无法获取%s的企业信息'%name)

def _parse_baidu_company_info(html):
	'''
		@function：解析百度企业信用提供的企业基本信息
		@output: list of dict, [{},{},...]
			pid: 跳转到具体企业页面的参数
			bid: 具体企业页面URL中的参数
			name: 企业名称
			type: 企业类型
			date: 成立日期
			address: 地址
			person: 法人代表
			status: 存续状态
			regCap: 注册资本
			scope: 经营范围
	'''
	js=re_get_js.findall(html)[1]
	data=re_resultList.search(js)
	if not data:
		return
	compant_list=json.loads(data.group(1))
	
	retVal=[]
	for x in compant_list:
		regCap=x['regCap'].replace(',','')
		if regCap[-1]=='万':
			regCap=regCap[:-1]
		regCap=float(regCap)
		address=x['domicile'].replace('<em>','').replace('</em>','')
		
		temp_v={'pid':x['pid'],'bid':x['bid'],'name':x['titleName'],'type':x['entType'],'date':x['validityFrom'],\
				'address':address,'person':x['legalPerson'],'status':x['openStatus'],'regCap':regCap}
		retVal.append(temp_v)
	return retVal

def __basic():
	statement='/26412/31243/24207/21457/34920/20110/67/83/68/78/65292/26410/21457/34920/20110/\
	20854/20182/24179/21488/65281/10/20316/32773/65306/119/105/108/100/95/111/114/97/110/103/\
	101/10/20010/20154/20027/39029/65306/104/116/116/112/115/58/47/47/98/108/111/103/46/99/115/\
	100/110/46/110/101/116/47/113/113/95/51/53/52/48/56/48/51/48/10/22914/26524/35273/24471/25991/\
	31456/26377/24110/21161/65292/27426/36814/28857/20010/36190/126/35874/35874/65281'
	info=statement.split('/')[1:]
	outVal=''
	for x in info:
		outVal+=chr(int(x))
	return outVal

def __check():
	global has_statement
	if has_statement is True:
		return True
	else:
		try:
			print(__basic()+'\n')
			has_statement=True
			return True
		except Exception as E:
			print(b'\xe7\xa8\x8b\xe5\xba\x8f\xe5\xb7\xb2\xe8\xa2\xab\xe5\x88\
			\xab\xe4\xba\xba\xe7\xaf\xa1\xe6\x94\xb9\xef\xbc\x81\xe6\xac\
			\xa2\xe8\xbf\x8e\xe5\x88\xb0CSDN\xe5\x85\xb3\xe6\xb3\xa8\xe5\
			\x8e\x9f\xe4\xbd\x9c\xe8\x80\x85\xef\xbc\x9awild_orange'.decode('utf-8'))
			return False
res=Get_company_info('运城深国投商用置业有限公司')
print(res)